package com.wlhse.service.impl;

import com.github.pagehelper.PageHelper;
import com.wlhse.dao.CheckItemDao;
import com.wlhse.dao.CompanyDao;
import com.wlhse.dao.PlanDao;
import com.wlhse.dao.TaskDao;
import com.wlhse.dto.inDto.PlanContentDto;
import com.wlhse.dto.inDto.PlanDto;
import com.wlhse.dto.inDto.TaskManagementDto;
import com.wlhse.dto.outDto.PlanOutDto;
import com.wlhse.entity.CheckItemPojo;
import com.wlhse.entity.CompanyPojo;
import com.wlhse.entity.Mail;
import com.wlhse.exception.WLHSException;
import com.wlhse.service.PlanService;
import com.wlhse.util.GetNamesUtil;
import com.wlhse.util.SendMessageUtil;
import com.wlhse.util.TreeUtil;
import com.wlhse.util.state_code.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;


@Service
public class PlanServiceImpl implements PlanService {

    @Resource
    private PlanDao planDao;

    @Resource
    private TreeUtil treeUtill;

    @Resource
    private PlanDto planDto;

    @Resource
    private CheckItemDao checkItemDao;

    @Resource
    private TaskDao taskDao;

    @Resource
    private TaskManagementDto taskManagementDto;

    @Resource
    private SendMessageUtil sendMessageUtil;

    @Resource
    private GetNamesUtil getNamesUtil;

    @Resource
    private CompanyDao companyDao;

    @Override
    //待审核
    @Transactional
    public String addPlan(PlanDto planDto, Integer userId) {
        List<PlanContentDto> listContent = planDto.getPlanContent();
        if (planDao.addPlan(planDto) <= 0)
            throw new WLHSException("新增失败");

        int Plan_ID = planDao.queryLastPlanID(planDto.getTaskCheckPersonsID());

        for (PlanContentDto dto : listContent) {
            dto.setPlanId(Plan_ID);
        }
        int taskID = planDto.getTaskID();
        TaskManagementDto taskManagementDto = taskDao.queryTasksByID(taskID, null, null, null, null);
        //发送信息
        Mail mail = sendMessageUtil.getMail(CodeDict.SEND_VERIFY, userId, taskManagementDto.getPublisherID(), taskManagementDto.getOrderNumber());
        sendMessageUtil.sendMessage(mail);

        if (planDao.addPlanContent(listContent) <= 0)
            throw new WLHSException("新增失败");
        return NR.r();
    }

    @Override
    @Transactional
    public String deletePlan(int planId) {
        //先删从表planContent
        List<PlanContentDto> listPlanDto = planDao.queryPlanContentsByPlanId(planId);
        planDao.deletePlanContent(listPlanDto);
        //再删主表plan
        planDao.deletePlan(planId);
        return NR.r();
    }

    @Override
    @Transactional(isolation = Isolation.SERIALIZABLE)
    public String updatePlan(PlanDto planDto) {
        List<PlanContentDto> lstPlanContent = planDto.getPlanContent();
        int i = 1;
        //从前端传来的planID和taskCheckPersonsID
        int planID = planDto.getPlanId();
        int taskCheckPersonsID = planDto.getTaskCheckPersonsID();
        //如果没传来planID，则为新增plan
        if (0 == planID) {
            i *= planDao.addPlan(planDto);
            //获取当前小任务的最后一个planID
            int lastPlanID = planDao.queryLastPlanID(taskCheckPersonsID);
            for (PlanContentDto dto : lstPlanContent) {
                dto.setPlanId(lastPlanID);
            }
            i *= planDao.addPlanContent(lstPlanContent);
            if (i <= 0)
                throw new WLHSException("更新失败");
            return NR.r();
        } else {
            planDao.deletePlanContentById(planID);
            planDao.deletePlan(planID);

            i *= planDao.addPlan(planDto);
            for (PlanContentDto dto : lstPlanContent) {
                dto.setPlanId(planID);
            }
            i *= planDao.addPlanContent(lstPlanContent);
            if (i <= 0)
                throw new WLHSException("新增失败");
            return NR.r();
        }
    }

    @Override
    @Transactional
    public String modifyPlan(PlanDto planDto) {
        int i;
        int j = 1;
        int k = 1;

        List<PlanContentDto> lstPlanContent = planDto.getPlanContent();
        int taskCheckPersonsID = planDto.getTaskCheckPersonsID();

        //如果状态为完成，需要额外判断完成的数量
        if (planDto.getStatus().length() > 0) {
            i = planDao.updatePlan(planDto);
            //如果状态为完成，需要额外判断完成的数量
            if (planDto.getStatus().equals("完成")) {
                int count1 = planDao.countByStatus("完成", planDto.getTaskCheckPersonsID());
                int count2 = planDao.countByStatus("", planDto.getTaskCheckPersonsID());
                if (count1 == count2) {
                    j = taskDao.updateTaskCheckPersonsStatus(planDto.getTaskCheckPersonsID(), planDto.getStatus(), planDto.getTaskID());
                    int count3 = taskDao.countByStatus("完成", planDto.getTaskID());
                    int count4 = taskDao.countByStatus("", planDto.getTaskID());
                    if (count3 == count4) {

                        //2.你的任务完成
                        TaskManagementDto taskManagementDto = taskDao.queryTasksByID(planDto.getTaskID(), null, null, null, null);
                        Mail mail = sendMessageUtil.getMail(CodeDict.SEND_TASK_FINISH, taskCheckPersonsID, taskManagementDto.getPublisherID(), taskManagementDto.getOrderNumber());
                        sendMessageUtil.sendMessage(mail);

                        this.taskManagementDto.setTaskID(planDto.getTaskID());
                        this.taskManagementDto.setStatus("完成");
                        k = taskDao.updateTask(this.taskManagementDto);
                    }
                }
            } else {
                TaskManagementDto dto = taskDao.queryTasksByPlanId(planDto.getPlanId());
                if (planDto.getStatus().equals("执行中")) {
                    Mail mail = sendMessageUtil.getMail(CodeDict.SEND_TASK_PASS, dto.getPublisherID(), dto.getLeaderID(), dto.getOrderNumber());
                    sendMessageUtil.sendMessage(mail);
                }
                if (planDto.getStatus().equals("审核不通过")) {
                    Mail mail = sendMessageUtil.getMail(CodeDict.SEND_TASK_NO_PASS, dto.getPublisherID(), dto.getLeaderID(), dto.getOrderNumber());
                    sendMessageUtil.sendMessage(mail);
                }
                if (planDto.getStatus().equals("未审核")) {
                    Mail mail = sendMessageUtil.getMail(CodeDict.SEND_VERIFY, planDto.getCheckPersonsID(), dto.getPublisherID(), dto.getOrderNumber());
                    sendMessageUtil.sendMessage(mail);
                }
                i = planDao.updatePlan(planDto);
            }
        } else {
            //修改plancontent
            planDao.deletePlanContentById(planDto.getPlanId());
            planDao.deletePlan(planDto.getPlanId());

            i = planDao.addPlan(planDto);
            int planID = planDao.queryLastPlanID(taskCheckPersonsID);
            for (PlanContentDto dto : lstPlanContent) {
                dto.setPlanId(planID);
            }
            j = planDao.addPlanContent(lstPlanContent);
        }
        if (i * j * k <= 0)
            throw new WLHSException("更新失败");
        return NR.r();
    }

    @Override
    public String getTreeDto(int planId) {
        //查询出全部的planContent
        List<CheckItemPojo> list = getList(planDao.queryPlanContentsByPlanId(planId));
        return NR.r(treeUtill.generalGetChechItemTree(list));
    }

    private List<CheckItemPojo> getList(List<PlanContentDto> planContentDtoList) {
        List<CheckItemPojo> list = new ArrayList<>();
        Set<String> set = new HashSet<>();
        for (PlanContentDto dto : planContentDtoList) {
            if (!set.contains(dto.getItem1())) {
                list.add(checkItemDao.queryByCheckItemCode(dto.getItem1()));
                set.add(dto.getItem1());
            }
            if (!set.contains(dto.getItem2())) {
                list.add(checkItemDao.queryByCheckItemCode(dto.getItem2()));
                set.add(dto.getItem2());
            }
            if (!set.contains(dto.getItem3())) {
                list.add(checkItemDao.queryByCheckItemCode(dto.getItem3()));
                set.add(dto.getItem3());
            }
        }
        return list;
    }

    @Override
    public String queryPlansByTaskID(PlanDto planDto) {
        List<PlanDto> list = planDao.queryPlansByTaskID(planDto.getTaskID());
        if (null == planDao.queryPlansByTaskID(planDto.getTaskID()))
            throw new WLHSException("查询失败");
        for (PlanDto plan : list) {
            String codes = plan.getCompanyCode();
            String companyNames = getNamesUtil.changeCompanyCodeToNamesSingle(codes);
            plan.setCompanyName(companyNames);
            if (null != planDao.queryPlanContentsByPlanId(plan.getPlanId())) {
                plan.setPlanContent(planDao.queryPlanContentsByPlanId(plan.getPlanId()));
            }
        }
        //分页
        if (planDto.getType().equals("all"))
            return NR.r(list);
        int total = planDao.queryTotalPlansByTaskID(planDto.getTaskID());//数据库查
        PageHelper.startPage(planDto.getPageIdx(), planDto.getPageSize());
        return NR.r(list, total, planDto.getPageIdx());
    }

    @Override
    public String getChooseNodeID(int planId) {
        //查询出全部的planContent
        List<PlanContentDto> planContentDtoList = planDao.queryPlanContentsByPlanId(planId);
        if (planContentDtoList.isEmpty()) {
            return NR.r(CodeDict.CODE_MESSAGE_DATA, 0, 0, null, null, 0, 0);
        } else {
            List<String> chooseNodeId = new ArrayList<>();

            for (PlanContentDto dto : planContentDtoList) {
                chooseNodeId.add(dto.getItem3());
            }
            return NR.r(CodeDict.CODE_MESSAGE_DATA, 0, 0, chooseNodeId, null, 0, 0);
        }
    }

    @Override
    public String queryPlanByID(int planId) {
        planDto = planDao.queryPlanByID(planId);
        if (null == planDto)
            throw new WLHSException("查询失败");
        String codes = planDto.getCompanyCode();
        String names = getNamesUtil.changeCompanyCodeToNamesSingle(codes);
        planDto.setCompanyName(names);
        return NR.r(planDto);
    }

    @Override
    public String queryPlanByCondition(PlanDto planDto) {
        int total = planDao.queryTotalPlanNoContentByCondition(planDto);
        if (total == 0)
            throw new WLHSException("查询失败");
        if (planDto.getType().equals("all")) {
            List<PlanOutDto> list = planDao.queryPlanNoContentByCondition(planDto);
            List<PlanOutDto> newList = getNamesUtil.changeCompanyCodeToNames(list);
            return NR.r(newList);
        }
        PageHelper.startPage(planDto.getPageIdx(), planDto.getPageSize());
        List<PlanOutDto> list = planDao.queryPlanNoContentByCondition(planDto);
        List<PlanOutDto> newList = getNamesUtil.changeCompanyCodeToNames(list);
        return NR.r(newList, total, planDto.getPageIdx());
    }

    @Override
    public String queryCurrentPersonByStatus(PlanDto planDto) {
        int total = planDao.queryTotalPlanByConditionSpecial(planDto);
        if (planDto.getType().equals("all")) {//不分页
            List<PlanOutDto> list1 = planDao.queryPlanByConditionSpecial(planDto);
            List<PlanOutDto> newList1 = getNamesUtil.changeCompanyCodeToNames(list1);
            return NR.r(newList1);
        }
        PageHelper.startPage(planDto.getPageIdx(), planDto.getPageSize());
        List<PlanOutDto> list1 = planDao.queryPlanByConditionSpecial(planDto);
        List<PlanOutDto> newList1 = getNamesUtil.changeCompanyCodeToNames(list1);
        return NR.r(newList1, total, planDto.getPageIdx());
    }

    @Override
    public String queryPlanCompany(Integer planId) {
        String companyString = planDao.getCompanyString(planId);
        String[] companyCodes = companyString.split(",");
        List<CompanyPojo> list = new ArrayList<>();
        for (String companyCode : companyCodes) {
            String companyName = companyDao.queryByCompanyCode(companyCode);
            CompanyPojo companyPojo = new CompanyPojo(companyCode, companyName);
            list.add(companyPojo);
        }
        return NR.r(list);
    }

}
